import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart' show defaultTargetPlatform, TargetPlatform;
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';
import 'package:provider/provider.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter/services.dart';
import 'package:stars_moon/core/auth_store.dart';
// removed external install plugin, using platform channel instead
// utils/common_utils.dart
class CommonUtils {
  static String versionPlatformParam() {
    switch (defaultTargetPlatform) {
      case TargetPlatform.iOS:
        return 'ios';
      case TargetPlatform.android:
        return 'android';
      case TargetPlatform.macOS:
        return 'macos';
      case TargetPlatform.windows:
        return 'windows';
      case TargetPlatform.linux:
        return 'linux';
      case TargetPlatform.fuchsia:
        return 'fuchsia';
    }
  }

  static Future<String> downloadFile(String url, {void Function(int received, int total)? onProgress}) async {
    final u = Uri.parse(url);
    final client = http.Client();
    final req = http.Request('GET', u);
    final resp = await client.send(req);
    final total = resp.contentLength ?? 0;
    final dir = await getTemporaryDirectory();
    final name = u.pathSegments.isNotEmpty ? u.pathSegments.last : 'download.bin';
    final file = File('${dir.path}/$name');
    final sink = file.openWrite();
    var received = 0;
    await for (final chunk in resp.stream) {
      received += chunk.length;
      sink.add(chunk);
      if (onProgress != null) onProgress(received, total);
    }
    await sink.close();
    client.close();
    return file.path;
  }

  static void quitApp() {
    try {
      SystemNavigator.pop();
    } catch (_) {
      exit(0);
    }
  }

  static Future<void> checkAndPromptUpdate(BuildContext context, {bool manual = false}) async {
    try {
      final info = await PackageInfo.fromPlatform();
      final version = info.version;
      final platform = CommonUtils.versionPlatformParam();
      final auth = Provider.of<AuthStore>(context, listen: false);
      final data = await auth.checkVersion(platform: platform, version: version);
      final updateType = (data['update_type'] ?? 'none').toString();
      final latest = (data['latest_version'] ?? '').toString();
      final log = (data['update_log'] ?? '').toString();
      final url = (data['download_url'] ?? '').toString();
      if (!manual && updateType == 'none') return;
      showDialog(
        context: context,
        builder: (_) => AlertDialog(
          title: Text(updateType == 'none' ? '已是最新版本' : '发现新版本 $latest'),
          content: SingleChildScrollView(child: Text(log.isEmpty ? '无更新说明' : log)),
          actions: [
            TextButton(
              onPressed: () {
                if (updateType == 'force') {
                  CommonUtils.quitApp();
                } else {
                  Navigator.of(context).pop();
                }
              },
              child: const Text('关闭'),
            ),
            if (url.isNotEmpty && updateType != 'none')
              TextButton(
                onPressed: () async {
                  if (defaultTargetPlatform == TargetPlatform.iOS) {
                    Navigator.of(context).pop();
                    try {
                      await launchUrl(Uri.parse(url), mode: LaunchMode.externalApplication);
                    } catch (e) {
                      if (updateType == 'force') {
                        CommonUtils.quitApp();
                      } else {
                        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('下载失败: $e')));
                      }
                    }
                    return;
                  }
                  Navigator.of(context).pop();
                  StateSetter? ss;
                  double p = 0;
                  int total = 0;
                  showDialog(
                    context: context,
                    barrierDismissible: false,
                    builder: (_) => StatefulBuilder(
                      builder: (ctx, setState) {
                        ss = setState;
                        return AlertDialog(
                          title: const Text('正在下载'),
                          content: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              LinearProgressIndicator(value: total > 0 ? p : null),
                              const SizedBox(height: 8),
                              Text(total > 0 ? '${(p * 100).toStringAsFixed(0)}%' : '正在连接'),
                            ],
                          ),
                          actions: [
                            TextButton(
                              onPressed: () {
                                if (updateType == 'force') {
                                  CommonUtils.quitApp();
                                } else {
                                  Navigator.of(ctx).pop();
                                }
                              },
                              child: const Text('取消'),
                            ),
                          ],
                        );
                      },
                    ),
                  );
                  try {
                    final path = await CommonUtils.downloadFile(url, onProgress: (r, t) {
                      total = t;
                      final v = t > 0 ? r / t : p;
                      if (ss != null) ss!((){ p = v; });
                    });
                    Navigator.of(context).pop();
                    if (defaultTargetPlatform == TargetPlatform.android) {
                      const channel = MethodChannel('app.installer');
                      await channel.invokeMethod('installApk', {'filePath': path});
                    } else {
                      await launchUrl(Uri.file(path), mode: LaunchMode.externalApplication);
                    }
                  } catch (e) {
                    Navigator.of(context).pop();
                    if (updateType == 'force') {
                      CommonUtils.quitApp();
                    } else {
                      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('下载失败: $e')));
                    }
                  }
                },
                child: const Text('前往下载'),
              ),
          ],
        ),
      );
    } catch (e) {
      if (manual) {
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('版本检测失败: $e')));
      }
    }
  }
}
